package ai.people.core.security.exception.handler;

import ai.people.netmon.framework.exception.enums.AuthExceptionEnum;
import ai.people.netmon.framework.model.response.Result;
import ai.people.netmon.framework.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 认证授权
 *
 * @author yuanqinglong
 * @date 2022/4/15 18:07
 */
@Order(10)
@RestControllerAdvice
public class UAAExceptionHandler {

    Logger logger = LoggerFactory.getLogger(UAAExceptionHandler.class);

    /**
     * 拒绝访问异常处理程序
     *
     * @param accessDeniedException 拒绝访问异常
     * @return {@link Result}<{@link T}>
     */
    @ExceptionHandler(AccessDeniedException.class)
    public <T> Result<T> accessDeniedExceptionHandler(AccessDeniedException accessDeniedException) {
        logger.error("accessDeniedException", accessDeniedException);
        return ResultUtil.error(AuthExceptionEnum.INSUFFICIENT_PERMISSIONS);
    }

    /**
     * 无效Token异常处理程序
     *
     * @param invalidTokenException 拒绝访问异常
     * @return {@link Result}<{@link T}>
     */
    @ExceptionHandler(InvalidTokenException.class)
    public <T> Result<T> invalidTokenExceptionHandler(InvalidTokenException invalidTokenException) {
        logger.error("invalidTokenException", invalidTokenException);
        return ResultUtil.error(AuthExceptionEnum.INVALID_TOKEN);
    }

    /**
     * 身份验证不足异常处理程序
     *
     * @param insufficientAuthenticationException 拒绝访问异常
     * @return {@link Result}<{@link T}>
     */
    @ExceptionHandler(InsufficientAuthenticationException.class)
    public <T> Result<T> insufficientAuthenticationExceptionHandler(InsufficientAuthenticationException insufficientAuthenticationException) {
        logger.error("insufficientAuthenticationException {}",AuthExceptionEnum.INVALID_TOKEN.getMessage(), insufficientAuthenticationException);
        return ResultUtil.error(AuthExceptionEnum.INVALID_TOKEN);
    }

}
